﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.Contract.ContractPcon.IPconDbMsgParsers;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.BaseConfigs;
using HamcoWcs.Entitys.Logss;
using HamcoWcs.Models.BaseConfigs;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using HamcoWcs.Service.Common;
using HamcoWcs.Workers.RouteWorkers;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Workers
{
    /// <summary>输送设备后台服务</summary>
    [DisallowConcurrentExecution]
    public partial class PconWorker : WorkerBase
    {

        private void DoWork(PconPlc pconPlc)
        {
            try
            {
                //DoTest(pconPlc);
                var isread = pconPlc.ReadDbBlock();
                if (!isread)
                {
                    _logger.AddSystemErrorLog($"{pconPlc.PlcName} PconWorker Con't Connect");
                    return;
                } 

                DealRecv(pconPlc);
                if (GlobalValue.PconRouteTick < GlobalValue.PconRouteTickThreshold)
                {
                    GlobalValue.PconRouteTick++;
                }
                else
                {
                    RouteWorker.ASRSInitFlag = true;
                }

                GlobalValue.PconInitFlag = true;
                DealTask(pconPlc);
                DealSend(pconPlc);
            }
            catch (Exception e)
            {
                _logger.AddSystemErrorLog("PconWorker:" + e.Message);
                pconPlc.DisconnectToPlc();
                return;
            }
            finally
            {
                try
                {
                    if (_communicationLogs?.Count > 0)
                        _logger.AddCommunicationLogs(_communicationLogs);
                }
                catch (Exception ex)
                {
                    _logger.AddSystemErrorLog($"PconWorker->DoWork->finally:Log communication error:{ex.Message}");
                }
            }
        }




        private void DoTest(PconPlc pconPlc)
        {
            var needPcons = new List<string>() { "CJMIFB00", "CJMIFC00", "CJRGV100", "CJRGV200" };
            var items = pconPlc.Pcons.Values.Where(x => needPcons.Contains(x.MachineName)).ToList();
            items.ForEach(x => 
            {
                x.IsGoods = 0;
                x.PconMode = 1;
                
            });
            foreach (var item in items)
            {
                _pconStateService.UpdateMachineState(item);
            }
        }
        public override Task Execute(IJobExecutionContext context)
        {
            try
            {
                var pcon = _pconBaseService.GetPconPlc(context.MergedJobDataMap.GetString("eqptSymbol"));
                DoWork(pcon);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return Task.CompletedTask;
        }

        #region Constructor

        public static Queue<RasterSendInfo> RASTER_SEND_BUFFERS = new Queue<RasterSendInfo>();
        public static Queue<MaterialSendInfo> MATERIAL_SEND_BUFFERS = new Queue<MaterialSendInfo>();
        private readonly IPconBaseService _pconBaseService;
        private readonly IPconMsgParseFactory _pconMsgParseFactory;
        private readonly IBaseTaskService _baseTaskService;
        private readonly IMonitorBaseService _monitorBaseService;
        private readonly IMesBaseService _mesBaseService;
        private readonly IPconStateService _pconStateService;
        private readonly IMesCommunicateService _mesCommunicateService;
        private readonly IPathService _pathService;
        private readonly AutomaticStorageInfo _asrs;
        private readonly List<CommunicationLog> _communicationLogs;
        private readonly IBaseConfigService _config;

        public PconWorker(IMapper mapper, WcsDbContext wcsDbContext, ILoggerService logger,
            IPconBaseService pconBaseService, IPconMsgParseFactory pconMsgParseFactory, IBaseTaskService baseTaskService,
            IMonitorBaseService monitorBaseService, IMesBaseService mesBaseService, IMesCommunicateService mesCommunicateService, IBaseConfigService baseConfigService,
            IPconStateService pconStateService, IPathService pathService, AutomaticStorageInfo asrs)
            : base(wcsDbContext, mapper, logger)
        {
            _pconBaseService = pconBaseService;
            _pconMsgParseFactory = pconMsgParseFactory;
            _baseTaskService = baseTaskService;
            _monitorBaseService = monitorBaseService;
            _mesBaseService = mesBaseService;
            _mesCommunicateService = mesCommunicateService;
            _pconStateService = pconStateService;
            _pathService = pathService;
            _asrs = asrs;
            _config = baseConfigService;
            _communicationLogs = new List<CommunicationLog>();

            if (GlobalValue.PconGlobalConfigs.Count == 0)
            {
                var cfgs = _wcsDbContext.Set<GlobalConfig>().Where(x => x.PlcType == "pcon").ToList();
                var cfgmodels = _mapper.Map<List<GlobalConfigModel>>(cfgs);

                foreach (var cfg in cfgmodels)
                {
                    GlobalValue.PconGlobalConfigs.Add(cfg.Name, cfg);
                }
            }
        }

        #endregion

    }
}
